﻿using MaterialSkin.Controls;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace FanermaAssist
{
    public partial class MainForm : Form
    {
        public string appkey = null;
        public string appsecret = null;
        public string CookieStr = null;

        
        

        public MainForm()
        {
            InitializeComponent();
        }

        private void btnlogin_Click(object sender, EventArgs e)
        {
            if (Process.GetProcessesByName("AlimamaLogin").Length > 0)
            {
                logmsg( "登录窗口已经打开。。。。请稍候！");
            }
            else
            {
                logmsg("正在打开登录窗口。。。。");
                string arguments = string.Format("\"{0}\" {1} {2} {3} 0", this.Text, checkBox1.Checked ? 1 : 0, this.txtAliAcc.Text, this.txtAliPwd.Text);
                Process.Start(Environment.CurrentDirectory + "\\AlimamaLogin.exe", arguments);

            }
        }


        public char[] char_message = new char[5000];
        private int char_message_int;

        protected override void DefWndProc(ref Message message)
        {
            try
            {
                if (message.Msg != 1125)
                {
                    base.DefWndProc(ref message);
                }
                else
                {
                    if (message.LParam == IntPtr.Zero)
                    {
                        this.char_message[this.char_message_int] = (char)((int)message.WParam);
                        this.char_message_int++;
                    }
                    else
                    {
                        int login_status_int = message.LParam.ToInt32();
                        CookieStr = Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(this.char_message, 0, this.char_message_int));
                        logmsg("阿里妈妈登录正常");
                        //AlimamaLogin.log_login(this, login_status_int, this.unicodeEncoding.GetString(this.unicodeEncoding.GetBytes(this.char_message, 0, this.char_message_int)));
                        this.char_message_int = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                logmsg("[DefWndProc]出错，" + ex.ToString());
            }
                
        }

        private void logmsg (string msg)
        {
            string text = this.richTextBox1.Text;
            this.richTextBox1.Text = string.Concat(new string[]
                    {
                        DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss"),
                        "----",
                        msg,
                        "\n",
                        text
                    });
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

            this.txtAliAcc.Text = Properties.Settings.Default.alimama_username;
            this.txtAliPwd.Text = Properties.Settings.Default.alimama_pwd;
            this.checkBox1.Checked = true;
            this.appkey = Properties.Settings.Default.alimama_appkey;
            this.appsecret = Properties.Settings.Default.alimama_appsecret;
        }
        //淘宝客商品查询
        public void  query_taobaoke()
        {
            string url = " http://gw.api.taobao.com/router/rest ";
            ITopClient client = new DefaultTopClient(url, appkey, appsecret,"json");
            TbkItemGetRequest req = new TbkItemGetRequest();
            req.Fields = "num_iid,title,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick";
            req.Q = "女装";
            req.Cat = "16,18";
            req.PageNo = 1;
            req.PageSize = 2;
            TbkItemGetResponse response = client.Execute(req);
            logmsg(response.Body.ToString());

        }
        //获取推广信息
        public static ArrayList query_campaign_list(string taoke_cookie, string num_iid, out string out_log)
        {
            string text = "";
            ArrayList result;
            try
            {
                out_log = "";
                string newValue = StringUtil.subString(taoke_cookie, 0, "_tb_token_=", ";");
                WebClient webClient = new WebClient();
                ArrayList arrayList = new ArrayList();
                long num = AlimamaUtil.current_time();
                webClient.Headers.Add("Accept", "application/json, text/javascript, */*; q=0.01");
                webClient.Headers.Add("X-Requested-With", "XMLHttpRequest");
                webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                webClient.Headers.Add("Referer", "http://pub.alimama.com/promo/search/index.htm?q=https%3A%2F%2Fitem.taobao.com%2Fitem.htm%3Fid%3D{itemId}&_t={timestamp}".Replace("{itemId}", num_iid).Replace("{timestamp}", string.Concat(num + 2100L)));
                webClient.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
                webClient.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
                webClient.Headers.Add("Cookie", taoke_cookie);
                string text2 = "http://pub.alimama.com/pubauc/getCommonCampaignByItemId.json?itemId={itemId}&t={timestamp}&_tb_token_={tbtoken}";
                string address = text2.Replace("{itemId}", num_iid).Replace("{timestamp}", string.Concat(num)).Replace("{tbtoken}", newValue);
                byte[] array = webClient.DownloadData(address);
                string value = webClient.ResponseHeaders["Content-Encoding"];
                if ("gzip".Equals(value))
                {
                    text = GzipUtil.zip_to_string(array, Encoding.UTF8);
                }
                else
                {
                    text = Encoding.UTF8.GetString(array);
                }
                if (text.Contains("\"data\":{}") || text.Contains("\"data\":[]") || text.Contains("\"data\":null"))
                {
                    out_log = text;
                    result = arrayList;
                }
                else
                {
                    if (text.Contains("\"wait\""))
                    {
                        out_log = text;
                        result = arrayList;
                    }
                    else
                    {
                        out_log = text;
                        string value2 = StringUtil.subString(text, 0, "{\"data\":[{", ":");
                        int num2 = 0;
                        while (true)
                        {
                            num2 = text.IndexOf(value2, num2);
                            if (num2 == -1)
                            {
                                break;
                            }
                            CampaignItem1 campaignItem = new CampaignItem1();
                            campaignItem.commissionRate = double.Parse(StringUtil.subString(text, num2, "\"commissionRate\":", ","));
                            campaignItem.CampaignID = StringUtil.subString(text, num2, "\"CampaignID\":", ",");
                            campaignItem.CampaignName = StringUtil.subString(text, num2, "\"CampaignName\":\"", "\",");
                            campaignItem.CampaignType = StringUtil.subString(text, num2, "\"CampaignType\":\"", "\",");
                            string text3 = StringUtil.subString(text, num2, "\"AvgCommission\":\"", "\",");
                            try
                            {
                                campaignItem.AvgCommission = double.Parse(text3.Replace("%", "").Replace(" ", ""));
                            }
                            catch
                            {
                                campaignItem.AvgCommission = 0.0;
                            }
                            campaignItem.Exist = StringUtil.subString(text, num2, "\"Exist\":", ",");
                            campaignItem.ShopKeeperID = StringUtil.subString(text, num2, "\"ShopKeeperID\":", ",");
                            campaignItem.Properties = StringUtil.subString(text, num2, "\"Properties\":", "\"");
                            campaignItem.manualAudit = int.Parse(StringUtil.subString(text, num2, "\"manualAudit\":", ","));
                            arrayList.Add(campaignItem);
                            num2++;
                        }
                        result = arrayList;
                    }
                }
            }
            catch (Exception ex)
            {
                out_log = "出错啦！！！" + text + "\n" + ex.ToString();
                result = null;
            }
            return result;
        }

        private List<string> getTaobaoItem()
        {
            List<string> lst = new List<string>();
            string itemlink = this.txtItem.Text;
            if (!string.IsNullOrEmpty(itemlink))
            {
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("id=(?<id>\\d+)");
                if (reg.IsMatch(itemlink))
                {
                    string itemid = reg.Match(itemlink).Groups["id"].Value;
                    lst.Add(itemid);
                }
            }
            
            return lst;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if ( string.IsNullOrEmpty(CookieStr) )
            {
                MessageBox.Show("请先登录阿里妈妈！");
                return;
            }
            String campaignsJson = null;
            //query_taobaoke();
            var iids = getTaobaoItem();
            foreach(string iid in iids)
            {
                ArrayList allCamains = query_campaign_list(CookieStr, iid, out campaignsJson);
                if (allCamains == null)
                {
                    logmsg("未找到推广计划！" + iid);
                }
                logmsg(FastJSON.JSON.Beautify(campaignsJson));
                if (allCamains.Count > 0)
                {
                    
                    var orderCamains = from u in allCamains.Cast<CampaignItem1>()                                 
                                       orderby u.commissionRate descending
                                       select u;
                    foreach (CampaignItem1 item in orderCamains)
                    {
                        String itemjson = FastJSON.JSON.ToJSON(item);
                        if ( item.Exist == "true")
                        {
                            logmsg("已申请过." );
                            break;
                        }
                        bool isok = false;
                        //按佣金高低，逐个申请
                        if ( item.manualAudit == 0)
                        {
                            //自动审核
                            logmsg("开始申请定向计划[自动审核]:" + item.CampaignName);
                        }
                        else
                        {
                            //人工审核
                            logmsg("开始申请定向计划[人工审核]:" + item.CampaignName);
                        }
                        string outmsg = null;
                        AlimamaUtil.apply_campaign(item.CampaignID, item.ShopKeeperID, Constants.applyreason_pre, Constants.applyreason_reason, CookieStr, out outmsg);
                        if (outmsg.Contains("\"wait\""))
                        {
                            logmsg("[apply_campaign_auto:]" + outmsg);
                            return;
                        }
                        logmsg("申请成功,佣金比例为："+ item.commissionRate);
                        //申请成功
                        if (isok) break;
                    }
                    

                }
            }            
        }
    }
}
